package com.hksj.em.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.cbm.service.DeviceInstanceService;
import com.hksj.cbm.vo.DeriveMetadataVO;
import com.hksj.em.query.DevicesInfoQuery;
import com.hksj.em.mapper.DevicesInfoMapper;
import com.hksj.em.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Component
public class DevicesInfoService {

    private static final Logger log = LoggerFactory.getLogger(DevicesInfoService.class);

    @Autowired
    private DevicesInfoMapper devicesInfoMapper;
    @Autowired
    private DeviceInstanceService deviceInstanceService;

    public Map<String, Integer> queryDevicesAmountByCode(@RequestBody DevicesInfoQuery query) {
        Map<String, Integer> map = devicesInfoMapper.queryDevicesAmountByCode(query);
        return map;
    }

    public IPage<DevicesVO> queryAirConditioningDevices(DevicesInfoQuery query) {
        // 创建分页对象
        Page<DevicesVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        // 查询设备列表
        List<DevicesVO> devicesList = devicesInfoMapper.queryAirConditioningDevices(page, query);

        log.info("查询到 {} 个空调设备", devicesList.size());
        // 获取所有设备的 ID 列表
        List<String> deviceIds = devicesList.stream().map(DevicesVO::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(deviceIds)) {
            // 批量查询设备属性、(id,物模型)
            Map<String, Map<String, DeriveMetadataVO>> deviceAttributeMap = deviceInstanceService.batchQueryDeviceAttribute(deviceIds);
            //设备属性
            List<DevidesPropertyVO> properties = devicesInfoMapper.selectDevidesPropertyByIds(deviceIds);
//            convertBooleanPropertiesInPlace(properties);
            // 构建设备属性映射表
            Map<String, List<DevidesPropertyVO>> propertyMap = properties.stream().collect(Collectors.groupingBy(DevidesPropertyVO::getDeviceId));
            // 填充设备属性
            populateDeviceAttributes(devicesList, deviceAttributeMap, propertyMap);
        }
        // 设置分页结果
        page.setRecords(devicesList);
        return page;
    }

    private void populateDeviceAttributes(List<DevicesVO> devicesList,
                                          Map<String, Map<String, DeriveMetadataVO>> deviceAttributeMap,
                                          Map<String, List<DevidesPropertyVO>> propertyMap) {
        devicesList.forEach(device -> {
            List<DeriveMetadataInfoVO> attributeList = new ArrayList<>();
            // 获取设备匹配的属性列表
            List<DevidesPropertyVO> matchedProperties = propertyMap.getOrDefault(device.getId(), Collections.emptyList());
            // 获取设备的默认属性映射
            Map<String, DeriveMetadataVO> defaultAttributes = deviceAttributeMap.getOrDefault(device.getId(), Collections.emptyMap());
            // 遍历默认属性并填充属性信息
            defaultAttributes.forEach((key, deriveMetadataVO) -> {
                // 根据 property 过滤出匹配的属性
                Optional<DevidesPropertyVO> resultOptional = matchedProperties.stream()
                        .filter(obj -> obj.getProperty().equals(key))
                        .findFirst();
                // 如果找到匹配的属性，则创建 DeriveMetadataInfoVO 并赋值
                resultOptional.ifPresent(result -> {
                    DeriveMetadataInfoVO infoVO = new DeriveMetadataInfoVO();
                    infoVO.setDeviceId(device.getId());
                    infoVO.setProperty(result.getProperty());
                    infoVO.setPropertyName(deriveMetadataVO.getKeyName());
                    infoVO.setDataType(deriveMetadataVO.getDataType());
                    infoVO.setCreateTime(result.getCreateTime());
                    infoVO.setNumberValue(result.getNumberValue());
                    infoVO.setValue(result.getValue());
                    infoVO.setUnit(result.getUnit());
                    infoVO.setCreateTime(result.getCreateTime());
                    infoVO.setStatus(result.getStatus());
                    infoVO.setPushType(result.getPushType());
                    infoVO.setAlarmStatus(result.getAlarmStatus());
                    infoVO.setRemark(result.getRemark());
                    infoVO.setReadWriteStatus(deriveMetadataVO.getReadWriteStatus());
                    // 将填充好的属性对象添加到列表中
                    attributeList.add(infoVO);
                });
            });
            // 将填充好的属性列表设置回设备
            device.setList(attributeList);
        });
    }


    /**
     * 将符合条件的属性对象直接转换为布尔值（原地修改）。
     *
     * @param properties 设备属性列表
     */
    public void convertBooleanPropertiesInPlace(List<DevidesPropertyVO> properties) {
        if (properties == null || properties.isEmpty()) {
            return; // 如果输入为空，直接返回
        }

        // 遍历列表并处理符合条件的属性
        properties.forEach(property -> {
            // 筛选出 dataType 为 "boolean" 的属性
            if ("boolean".equalsIgnoreCase(property.getDataType())) {
                if (property.getNumberValue() != null) {
                    try {
                        // 解析 numberValue 并判断是否为 1.0
                        boolean booleanValue = Double.parseDouble(property.getNumberValue()) == 1.0;
                        property.setNumberValue(String.valueOf(booleanValue)); // 设置布尔值
                    } catch (NumberFormatException e) {
                        log.error("Invalid number format for property: {}", property, e);
                        property.setNumberValue(String.valueOf(false)); // 默认值为 false
                    }
                } else {
                    property.setNumberValue(String.valueOf(false)); // 如果 numberValue 为空，默认值为 false
                }
            }
        });
    }


    public IPage<LightingDevicesVO> queryLightingsInfoByPage(DevicesInfoQuery query) {
        // 创建分页对象
        Page<LightingDevicesVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        List<LightingDevicesVO> list = devicesInfoMapper.queryLightingsInfoByPage(query);
        List<String> collect = list.stream().map(LightingDevicesVO::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            List<LightingPropertyVO> properties = devicesInfoMapper.selectLightingPropertyByIds(collect);
            Map<String, List<LightingPropertyVO>> propertyMap = properties.stream().collect(Collectors.groupingBy(LightingPropertyVO::getModelId));
            list.forEach(item -> {
                List<LightingPropertyVO> matchedProperties = propertyMap.getOrDefault(item.getId(), Collections.emptyList());
                item.setList(matchedProperties);
            });
        }
        // 设置分页结果
        page.setRecords(list);
        return page;
    }
}
